﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Friedlich.Common;
using DotNetOpenAuth.ApplicationBlock;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using DotNetOpenAuth.OAuth.ChannelElements;
using DotNetOpenAuth.OAuth;

namespace Friedlich.Delicious
{
    public class DeliciousFactory : IDeliciousFactory
    {

        public TagCollection GetTags() {
            XDocument tagDoc = null;
            var delicious = new WebConsumer(DeliciousConsumer.ServiceDescription, this.TokenManager);
            if (delicious != null)
            {
                if (this.AccessToken != null)
                {
                    tagDoc = DeliciousConsumer.GetTags(delicious,this.AccessToken);
                }
                else
                {
                    var accessTokenResponse = delicious.ProcessUserAuthorization();
                    if (accessTokenResponse != null)
                    {
                        this.AccessToken = accessTokenResponse.AccessToken;
                    }
                }
            }
            return ParseTags(tagDoc);            
        }


        public IConsumerTokenManager TokenManager { get; set; }

        public string AccessToken { get; set; }


        public virtual TagCollection GetSuggestedTags(string url) {
            XDocument tagDoc = null;
            var delicious = new WebConsumer(DeliciousConsumer.ServiceDescription, this.TokenManager);
            if (delicious != null)
            {
                if (this.AccessToken != null)
                {
                    tagDoc = DeliciousConsumer.GetTagSuggestions(delicious, this.AccessToken,url);
                }
                else
                {
                    var accessTokenResponse = delicious.ProcessUserAuthorization();
                    if (accessTokenResponse != null)
                    {
                        this.AccessToken = accessTokenResponse.AccessToken;
                    }
                }
            }
            return ParseTags(tagDoc);

        }

        protected TagCollection ParseTags(XDocument tagDoc)
        {
            TagCollection tags = new TagCollection();
            if (tagDoc != null)
            {                
                foreach (XElement tagElm in tagDoc.Root.Elements("tag"))
                {
                    XAttribute tagAttr = tagElm.Attribute("tag");
                    if (tagAttr != null)
                    {
                        Tag tag = new Tag();
                        tag.Label = tagAttr.Value;
                        tags.Add(tag);
                    }
                }
            }
            return tags;
        }

        public static string ApplicationName { get { return "Delicious"; } }
    }



}
